package online.zhangwenzhe.common.resultwarper;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Description
 * 简单类型返回结果自动包装成json
 * 总感觉存在隐患，不适合发布
 * Date这种类型，目前不好判断，穷举所有，感觉不适合
 *
 * @author zhangwenzhe
 * @since 2019-03-05
 */
@Deprecated
@ControllerAdvice
public class ResponseAdvisor implements ResponseBodyAdvice<Object> {


    //todo: 配置文件读取开关

    private boolean enable = false;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        if (body == null) {
            return body;
        }

        if (!enable) {
            return body;
        }

        Class className = body.getClass();
        if (className.equals(java.lang.Integer.class) ||
                className.equals(java.lang.Byte.class) ||
                className.equals(java.lang.Long.class) ||
                className.equals(java.lang.Double.class) ||
                className.equals(java.lang.Float.class) ||
                className.equals(java.lang.Character.class) ||
                className.equals(java.lang.Short.class) ||
                className.equals(java.lang.Boolean.class)) {
            return new JsonResult(body);
        }
        // String报错，要单独处理
        if (className.equals(java.lang.String.class)) {
            response.getHeaders().setContentType(MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE));
            body = "{\"value\":\"" + body + "\"}";
        }

        return body;
    }
}
